package com.hj.dapp.config.security;

import com.hj.dapp.business.user.model.User;
import com.hj.dapp.business.user.service.UserService;
import com.hj.dapp.common.util.ExpUtil;
import com.hj.dapp.common.util.JwtUtil;
import com.hj.dapp.common.util.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.hj.dapp.config.exp.BusinessErrorEnum.NO_LOGIN;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2023/12/29
 */
@Slf4j
public class JwtVerifyFilter extends OncePerRequestFilter {
    private UserService userService;

    public JwtVerifyFilter(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (token == null){
            chain.doFilter(request,response);
            return;
        }
        String userName = null;
        try {
            userName = JwtUtil.getUserName(token, RsaUtils.getPublicKey());
        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        UserDetails details = userService.loadUserByUsername(userName);
        if (details!=null){
            Authentication authentication = new UsernamePasswordAuthenticationToken
                    (details.getUsername(),null,details.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request,response);
        }

    }
}
